;(function () {
  const state = {
    hls: null,
    currentIdx: -1,
    minimized: false,
    episodes: [], // [{title, url}]
  };

  // DOM
  const $ = (sel) => document.querySelector(sel);
  const screenEl   = $('#playerScreen');
  const epListEl   = $('#epList');
  const videoEl    = $('#screen-video');
  const nowTitleEl = $('#nowTitle');
  const statusEl   = $('#screen-status');
  const closeBtn   = $('#screen-close');
  const minBtn     = $('#screen-min');
  const bodyEl     = $('.scr-body');
  const footerEl   = $('.scr-footer');

  function ensureDom() {
    if (!screenEl || !epListEl || !videoEl) {
      console.error('[screen] DOM not found. Did you include player HTML?');
      return false;
    }
    return true;
  }

  function renderEpisodes() {
    epListEl.innerHTML = '';
    state.episodes.forEach((ep, i) => {
      const btn = document.createElement('button');
      btn.className = 'ep-btn';
      btn.textContent = ep.title || `第${String(i+1).padStart(2,'0')}集`;
      btn.addEventListener('click', () => play(i));
      epListEl.appendChild(btn);
    });
  }

  function markActive(idx) {
    [...epListEl.children].forEach((b, i) => b.classList.toggle('active', i === idx));
  }

  function setStatus(msg) {
    if (statusEl) statusEl.textContent = msg || '';
  }

  function destroyHls() {
    try { state.hls && state.hls.destroy(); } catch {}
    state.hls = null;
    videoEl.removeAttribute('src');
    videoEl.load();
  }

  function play(idx) {
    const ep = state.episodes[idx];
    if (!ep) return;

    state.currentIdx = idx;
    markActive(idx);
    nowTitleEl.textContent = ep.title || `第${String(idx+1).padStart(2,'0')}集`;
    setStatus('加载中…');

    const url = (ep.url || '').trim();
    destroyHls();

    if (/\.m3u8(\?|$)/i.test(url)) {
      if (window.Hls && window.Hls.isSupported()) {
        state.hls = new Hls();
        state.hls.on(Hls.Events.MANIFEST_PARSED, () => setStatus('已加载，可播放'));
        state.hls.on(Hls.Events.ERROR, (e, data) => setStatus('播放错误：' + (data?.details || data?.type || 'unknown')));
        state.hls.loadSource(url);
        state.hls.attachMedia(videoEl);
        videoEl.play().catch(()=>{});
      } else if (videoEl.canPlayType('application/vnd.apple.mpegurl')) {
        videoEl.src = url;
        videoEl.play().catch(()=>{});
        setStatus('已加载（Safari）');
      } else {
        setStatus('当前浏览器不支持 HLS');
      }
    } else {
      // mp4
      videoEl.src = url;
      videoEl.play().then(()=>setStatus('已加载')).catch(()=>setStatus('自动播放被阻止'));
    }
  }

  function open(episodes) {
    if (!ensureDom()) return;
    state.episodes = Array.isArray(episodes) ? episodes : [];
    renderEpisodes();

    screenEl.classList.remove('hidden');
    screenEl.setAttribute('aria-hidden', 'false');

    if (state.currentIdx === -1 && state.episodes.length) {
      play(0);
    }
  }

  function close() {
    destroyHls();
    screenEl.classList.add('hidden');
    screenEl.setAttribute('aria-hidden', 'true');
  }

  function toggleMin() {
    state.minimized = !state.minimized;
    screenEl.style.height = state.minimized ? '120px' : '';
    bodyEl.style.display   = state.minimized ? 'none' : 'grid';
    footerEl.style.display = state.minimized ? 'none' : 'flex';
  }

  // 事件
  if (closeBtn) closeBtn.addEventListener('click', close);
  if (minBtn)   minBtn.addEventListener('click', toggleMin);

  // 对外暴露
  window.openScreenPlayer = open;   // openScreenPlayer([{title,url},...])
  window.closeScreenPlayer = close; // 可选
})();